package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

/**
 * 图片上传类
 * @author Administrator
 *
 */
public class UploadDownUtil {
	/**
	 * 
	 * @param files 文件集合
	 * @param filesName  文件名称
	 * @return List<String>  新的文件名称集合
	 */
public static List<String> upload( List<File> files,List<String> filesName,String folder){
	List<String> list=new ArrayList<String>();
	try {
		if (files != null && files.size() > 0) {
	        for (int i = 0; i < files.size(); i++) {
	        	// 新的文件名
	        	String newFileName=getName(filesName.get(i));
	        	list.add(newFileName);
	            FileOutputStream fos = new FileOutputStream(getSavePath(newFileName,folder));
	            FileInputStream fis = new FileInputStream(files.get(i));
	            byte[] buffer = new byte[1024];
	            int len = 0;
	            while ((len = fis.read(buffer)) > 0) {
	                fos.write(buffer, 0, len);
	            }
	            fis.close();
	            fos.close();
	        }
	     }
	} catch (Exception e) {
		e.printStackTrace();
	}
	return list;
}

	//单个文件上传
	public static String upload(File file,String path){
		String fileName = UUID.randomUUID().toString().replace("-", "")+".jpg";
		String realPath = path+"/"+fileName;
		try {
			FileOutputStream fos = new FileOutputStream(realPath);
			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
			    fos.write(buffer, 0, len);
			}
			fis.close();
			fos.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
		
// 重命名图片的名字避免重复
private static  String getName(String fileName){
   int i=fileName.indexOf('.');
	return UUID.randomUUID().toString().replace("-", "")+fileName.substring(i);
}
// 获取容器的绝对路径
private static  String getSavePath(String newFileName,String folder) {
	//return ServletActionContext.getServletContext().getRealPath("/upload")+"/"+folder+"/"+newFileName;
	String path = System.getProperty("user.dir");
	path = path.replace("bin", "webapps");
	path=path+"\\oil_web\\upload\\"+folder+"\\"+newFileName;
	System.out.println(path);
	return path;
	
}

}
